<template>
    <div>
        <div class="ruleMessage" v-if="ruleMessage">
            {{ ruleMessage }}
        </div>
        <div class="e-table" style="background-color: #fff">
            <!-- 头部buttons -->
            <div class="top">
                <div>
                    <div class="left">
                        <div v-if="auditState.canModify">
                            <!-- 物资加工 -->
                            <div v-if="serviceType === 1">
                                <el-button
                                    size="small"
                                    class="btn-greenYellow"
                                    @click="selectBaseLibrary"
                                    style="margin-left: 10px"
                                    >选择基础库</el-button
                                >
                            </div>
                            <!-- 设备维修 -->
                            <div v-else-if="serviceType === 2">
                                <el-dropdown @command="selectEquiPlan">
                                    <el-button size="small" class="btn-greenYellow"
                                        >选择计划<i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item :command="1"
                                            >设备大修计划</el-dropdown-item
                                        >
                                        <el-dropdown-item :command="2"
                                            >维保申请汇总</el-dropdown-item
                                        >
                                        <el-dropdown-item :command="3">设备台账</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                                <el-button
                                    size="small"
                                    class="btn-greenYellow"
                                    @click="selectEquiBaseLibrary"
                                    style="margin-left: 10px"
                                    >选择基础库</el-button
                                >
                            </div>
                            <!-- 设备安装 -->
                            <div v-else-if="serviceType === 3">
                                <el-dropdown @command="selectEquiPlan">
                                    <el-button size="small" class="btn-greenYellow"
                                        >选择计划<i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item :command="3">设备台账</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                                <el-button
                                    size="small"
                                    class="btn-greenYellow"
                                    @click="selectEquiBaseLibrary"
                                    style="margin-left: 10px"
                                    >选择基础库</el-button
                                >
                            </div>
                            <div v-else-if="serviceType === 4">
                                <el-dropdown @command="selectEquiPlan">
                                    <el-button size="small" class="btn-greenYellow"
                                        >选择计划<i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                    <el-dropdown-menu slot="dropdown">
                                        <el-dropdown-item :command="1"
                                            >设备大修计划</el-dropdown-item
                                        >
                                        <el-dropdown-item :command="2"
                                            >维保申请汇总</el-dropdown-item
                                        >
                                        <el-dropdown-item :command="3">设备台账</el-dropdown-item>
                                    </el-dropdown-menu>
                                </el-dropdown>
                                <el-button
                                    size="small"
                                    class="btn-greenYellow"
                                    @click="selectBaseLibrary"
                                    style="margin-left: 10px"
                                    >选择物资基础库</el-button
                                >
                                <el-button
                                    size="small"
                                    class="btn-greenYellow"
                                    @click="selectEquiBaseLibrary"
                                    style="margin-left: 10px"
                                    >选择设备基础库</el-button
                                >
                            </div>
                        </div>
                        <el-select
                            v-model="detailsDataCurDtlId"
                            placeholder="请选择包件"
                            style="width: 300px; margin-left: 10px"
                            @change="handleNodeClick"
                        >
                            <el-option
                                v-for="item in detailsData"
                                :key="item.dtlId"
                                :label="item.itemNo + ' ' + item.name"
                                :value="item.dtlId"
                            >
                            </el-option>
                        </el-select>
                    </div>
                </div>
            </div>
            <el-table
                :data="tableData[dtlIndex]"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
                v-if="serviceType === 1 || serviceType === 4"
                :key="dtlIndex"
                :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
                @cell-click="cellClick"
            >
                <el-table-column width="120" label="操作" v-if="auditState.canModify">
                    <!--                                 :class="{
                                    'icon-delete-active-color': MouseEnterId == scope.row.dtlId
                                }" -->
                    <template slot-scope="scope">
                        <i
                            slot="reference"
                            class="el-icon-delete"
                            style="cursor: pointer; font-size: 20px"
                            @click="deleteData(scope.$index)"
                        ></i>
                    </template>
                </el-table-column>
                <el-table-column prop="type" label="物资类别" min-width="200"> </el-table-column>
                <el-table-column prop="name" label="物资名称" width="100"> </el-table-column>
                <el-table-column prop="unit" label="单位" width="100"> </el-table-column>
                <el-table-column prop="specs" label="规格型号" width="100"> </el-table-column>
                <el-table-column prop="texture" label="材质" width="100"> </el-table-column>
                <el-table-column prop="num" label="数量" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.num"
                            placeholder="请输入内容"
                            v-enterFloat2="{
                                set: row,
                                key: 'num'
                            }"
                            @input="input(row)"
                            @blur="inputblur(row, 'num')"
                            v-if="
                                Object.keys(auditState).length !== 0 &&
                                Object.values(auditState).find(item => item === true)
                            "
                        >
                            <i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'numUpdateHistory')"
                                v-if="row.numUpdateHistory && row.numUpdateHistory.length !== 0"
                            ></i>
                        </el-input>
                        <span v-else>
                            {{ row.num }}
                            <i
                                class="el-icon-tickets"
                                style="margin-left: 5px"
                                v-if="row.numUpdateHistory && row.numUpdateHistory.length !== 0"
                                @click="priceHistory(row, 'numUpdateHistory')"
                            ></i>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="limitPrice" label="物资申报单价（元）" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.limitPrice"
                            placeholder="请输入内容"
                            v-enterFloat="{
                                set: row,
                                key: 'limitPrice'
                            }"
                            @input="input(row)"
                            @blur="inputblur(row, 'limitPrice')"
                            v-if="
                                Object.keys(auditState).length !== 0 &&
                                Object.values(auditState).find(item => item === true)
                            "
                        >
                            <i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'limitPriceUpdateHistory')"
                                v-if="
                                    row.limitPriceUpdateHistory &&
                                    row.limitPriceUpdateHistory.length !== 0
                                "
                            ></i>
                        </el-input>
                        <span v-else>
                            {{ row.limitPrice }}
                            <i
                                class="el-icon-tickets"
                                style="margin-left: 5px"
                                v-if="
                                    row.limitPriceUpdateHistory &&
                                    row.limitPriceUpdateHistory.length !== 0
                                "
                                @click="priceHistory(row, 'limitPriceUpdateHistory')"
                            ></i>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="freightPrice" label="运费申报单价（元）" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.freightPrice"
                            placeholder="请输入内容"
                            v-enterFloat="{
                                set: row,
                                key: 'freightPrice'
                            }"
                            @input="input(row)"
                            @blur="inputblur(row, 'freightPrice')"
                            v-if="
                                Object.keys(auditState).length !== 0 &&
                                Object.values(auditState).find(item => item === true)
                            "
                            ><i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'freightPriceUpdateHistory')"
                                v-if="
                                    row.freightPriceUpdateHistory &&
                                    row.freightPriceUpdateHistory.length !== 0
                                "
                            ></i>
                        </el-input>
                        <span v-else>
                            {{ row.freightPrice }}
                            <i
                                class="el-icon-tickets"
                                style="margin-left: 5px"
                                v-if="
                                    row.freightPriceUpdateHistory &&
                                    row.freightPriceUpdateHistory.length !== 0
                                "
                                @click="priceHistory(row, 'freightPriceUpdateHistory')"
                            ></i>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="综合单价（元）" width="120">
                </el-table-column>
                <el-table-column prop="amount" label="总金额（元）" width="120"> </el-table-column>
            </el-table>
            <el-table
                :data="tableData[dtlIndex]"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
                :tree-props="{
                    children: 'children',
                    hasChildren: 'hasChildren'
                }"
                v-else
                :key="dtlIndex"
                :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
            >
                <el-table-column width="120" label="操作" v-if="auditState.canModify">
                    <!--                                 :class="{
                                    'icon-delete-active-color': MouseEnterId == scope.row.dtlId
                                }" -->
                    <template slot-scope="scope">
                        <i
                            slot="reference"
                            class="el-icon-delete"
                            style="cursor: pointer; font-size: 20px"
                            @click="deleteData(scope.$index)"
                        ></i>
                    </template>
                </el-table-column>
                <el-table-column prop="equipmentNumber" label="设备编号" width="200">
                </el-table-column>
                <el-table-column prop="name" label="设备名称" width="100"> </el-table-column>
                <el-table-column prop="unit" label="单位" width="100"> </el-table-column>
                <el-table-column prop="specs" label="规格型号" width="100"> </el-table-column>
                <el-table-column prop="equipmentStatus" label="设备现状" width="100">
                </el-table-column>
                <el-table-column prop="maintenanceContent" label="维修内容" width="200">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.maintenanceContent"
                            placeholder="请输入内容"
                        ></el-input>
                    </template>
                </el-table-column>
                <el-table-column prop="num" label="数量" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.num"
                            placeholder="请输入内容"
                            v-enterFloat2="{
                                set: row,
                                key: 'num'
                            }"
                            @input="input(row)"
                            v-if="
                                auditState.canModify &&
                                Object.values(auditState).find(item => item === true)
                            "
                        >
                            <i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'numUpdateHistory')"
                                v-if="row.numUpdateHistory && row.numUpdateHistory.length !== 0"
                            ></i>
                        </el-input>
                        <span v-else>
                            {{ row.num }}
                            <i
                                class="el-icon-tickets"
                                style="margin-left: 5px"
                                v-if="row.numUpdateHistory && row.numUpdateHistory.length !== 0"
                                @click="priceHistory(row, 'numUpdateHistory')"
                            ></i>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="limitPrice" label="申报单价（元）" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.limitPrice"
                            placeholder="请输入内容"
                            v-enterFloat="{
                                set: row,
                                key: 'limitPrice'
                            }"
                            @input="input(row)"
                            v-if="
                                auditState.canModify &&
                                Object.values(auditState).find(item => item === true)
                            "
                        >
                            <i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'limitPriceUpdateHistory')"
                                v-if="
                                    row.limitPriceUpdateHistory &&
                                    row.limitPriceUpdateHistory.length !== 0
                                "
                            ></i>
                        </el-input>
                        <span v-else>
                            {{ row.limitPrice }}
                            <i
                                class="el-icon-tickets"
                                style="margin-left: 5px"
                                v-if="
                                    row.limitPriceUpdateHistory &&
                                    row.limitPriceUpdateHistory.length !== 0
                                "
                                @click="priceHistory(row, 'limitPriceUpdateHistory')"
                            ></i>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="freightPrice" label="运费申报单价（元）" width="150">
                    <template slot-scope="{ row }">
                        <el-input
                            v-model="row.freightPrice"
                            placeholder="请输入内容"
                            v-enterFloat="{
                                set: row,
                                key: 'freightPrice'
                            }"
                            @input="input(row)"
                            v-if="
                                auditState.canModify &&
                                Object.values(auditState).find(item => item === true)
                            "
                            ><i
                                slot="suffix"
                                class="el-icon-tickets"
                                @click="priceHistory(row, 'freightPriceUpdateHistory')"
                                v-if="
                                    row.freightPriceUpdateHistory &&
                                    row.freightPriceUpdateHistory.length !== 0
                                "
                            ></i>
                        </el-input>
                        <span v-else>
                            {{ row.freightPrice }}
                            <i
                                class="el-icon-tickets"
                                style="margin-left: 5px"
                                v-if="
                                    row.freightPriceUpdateHistory &&
                                    row.freightPriceUpdateHistory.length !== 0
                                "
                                @click="priceHistory(row, 'freightPriceUpdateHistory')"
                            ></i>
                        </span>
                    </template>
                </el-table-column>
                <el-table-column prop="unitPrice" label="综合单价（元）" width="120">
                </el-table-column>
                <el-table-column prop="amount" label="总金额（元）" width="120"> </el-table-column>
            </el-table>
        </div>
        <!-- dialog -->
        <el-dialog :visible.sync="historyDialogVisible" width="70%">
            <el-table
                :data="priceHistoryTableData"
                style="width: 100%; margin-bottom: 20px"
                row-key="id"
                border
                default-expand-all
                :max-height="$store.state.tableHeight"
            ref="table"
            v-sortTable="{ tableData: tableData, _this: this, ref: 'table' }"
            >
                <el-table-column prop="modifier" label="操作人" width="200"> </el-table-column>
                <el-table-column prop="createTime" label="核准日期" width="100"> </el-table-column>
                <el-table-column prop="originalContent" label="原数据" width="100">
                </el-table-column>
                <el-table-column prop="modifiedContent" label="核准数据" width="100">
                </el-table-column>
                <el-table-column prop="remarks" label="审核意见" width="100"> </el-table-column>
            </el-table>
            <span slot="footer" class="dialog-footer">
                <el-button @click="historyDialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
// import ComTreeTable from '@/templates/table/treeTable.vue'
// import ComTreeFile from '@/templates/table/treeFile.vue'
// import applyRequest from '@/api/tender/apply.js'
// eslint-disable-next-line no-unused-vars
import { selectDataClient, openAppClient } from '@/utils/common'
// import { vueDom } from '@/utils/common.js'
import materialServiceProcurementRequest from '@/api/tender/materialServiceProcurement.js'
import { mapState, mapMutations } from 'vuex'

export default {
    props: {
        // 包件数据
        detailsData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 清单数据
        tableData: {
            type: Array,
            default: function () {
                return []
            }
        },
        // 审核状态
        auditState: {
            type: Object,
            default: function () {
                return {}
            }
        },
        // 服务类型
        serviceType: {
            type: Number,
            required: true
        }
    },
    model: {
        prop: 'tableData',
        event: 'change'
    },
    data () {
        return {
            detailsOfProposedArr: [],
            // tableData: [],
            cloneTableData: [],
            dtlId: '',
            deleteTableData: [],
            tempArr: [], //临时用来保存清单，tabledata不能直接操作
            historyDialogVisible: false,
            priceHistoryTableData: [],
            ruleMessage: '',
            detailsDataCurDtlId: '',
            selectDetailState: false
        }
    },
    computed: {
        ...mapState({
            options: state => state.biddingApplication.dictionaries
        }),
        tenderId () {
            return this.$route.query.tenderId || this.$route.query.billid
        },
        // 当前选择包件的index
        dtlIndex () {
            return this.detailsData.findIndex(item => this.dtlId === item.dtlId)
        },
        // 当前选择包件名字
        dtlName () {
            return this.detailsData.find(item => this.dtlId === item.dtlId).name
        }
    },
    watch: {
        // 包件数据
        detailsData: {
            handler (newVal) {
                // 处理数据获得包件列表
                this.getDetails()
                if (newVal.length === 0) {
                    this.$emit('change', [])
                    // this.tableData = []
                    this.dtlId = ''
                    this.detailsDataCurDtlId = ''
                } else {
                    // 如果没选择过包件，包件id就默认第一个
                    if (this.dtlId === '' && this.selectDetailState === false) {
                        this.dtlId = newVal[0].dtlId
                    } else {
                        // 寻找当前包件数据里是否有当前id（主要判断被删情况）
                        const findVal = newVal.find(item => item.dtlId === this.dtlId)
                        if (findVal) {
                            this.dtlId = findVal.dtlId
                        } else {
                            this.dtlId = ''
                        }
                    }
                }
                // if (newVal.length === 1) {
                //     setTimeout(() => {
                //         $('.el-tree-node:first')?.addClass('is-current')
                //     }, 100)
                // }
            },
            deep: true
        },
        // 包件id
        dtlId (newVal) {
            this.detailsDataCurDtlId = newVal
            if (
                newVal !== '' &&
                JSON.stringify(this.tableData[this.dtlIndex]) ===
                    JSON.stringify(this.cloneTableData[this.dtlIndex])
            ) {
                this.getData() // 获取清单数据
            }
            // 工程tableData对应的是当前table，物资、设备对应的是所有table，删除包件只应该置空对应的table，而不是所有table，上面已经将dtlId找不到就置为空，所以tableData[this.dtlIndex]是找不到的。
            // if (newVal === '') {
            //     this.tableData = []
            // }
        },
        // 服务类型
        serviceType: {
            handler () {
                this.getData()
            },
            deep: true
        }
    },
    components: {
        // ComTreeTable,
        // ComTreeFile
    },
    created () {
        setTimeout(() => {
            console.log('auditState', this.auditState)
        }, 2000)
        // this.findByApplyId() // 获取包件列表数据
    },
    mounted () {
        // vueDom(
        //     // 默认0为选中项
        //     () => {
        //         $('.el-tree-node:first')?.addClass('is-current')
        //     },
        //     () => {
        //         return false
        //         //  $('.el-tree-node:first')?.attr('class')?.includes('is-current')
        //     }
        // )
        // setTimeout(() => {
        //     $('.el-tree-node:first')?.addClass('is-current')
        // }, 1000)
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),
        cellClick (row) {
            console.log('row', row)
        },
        inputblur (row, val) {
            row[val] = isNaN(parseFloat(row[val])) ? 0 : parseFloat(row[val])
        },
        priceHistory (row, arg) {
            this.historyDialogVisible = true
            this.priceHistoryTableData = row[arg]
        },
        deleteData (index) {
            this.tableData.forEach(() => {
                this.deleteTableData.push([])
            })
            if (this.tableData[this.dtlIndex][index].changeType !== 1) {
                this.tableData[this.dtlIndex][index].changeType = -1
                this.deleteTableData[this.dtlIndex].push(this.tableData[this.dtlIndex][index])
            }
            this.tableData[this.dtlIndex].splice(index, 1)
        },
        getData (dtlId = this.dtlId, dtlIndex = this.dtlIndex) {
            // console.log('getData', this.tableData, this.dtlIndex)
            // console.log('blur', this.tableData[this.dtlIndex].find(item => item.changeType !== 0) !== undefined)
            // 如果当前包件清单有数据则不查询
            // if (this.tableData[this.dtlIndex] !== undefined) return
            // 如果当前包件清单修改过则不查询
            // if (
            //     (this.tableData[this.dtlIndex] !== undefined &&
            //         this.tableData[this.dtlIndex].find(item => item.changeType !== 0) ===
            //             undefined)
            // )
            //     return
            // console.log('this.deleteTableData', this.deleteTableData)
            // if (arg !== 0) {
            //     if (
            //         this.tableData[this.dtlIndex]?.find(item => item.changeType !== 0) !==
            //             undefined ||
            //         (this.deleteTableData[this.dtlIndex] !== undefined &&
            //             this.deleteTableData[this.dtlIndex]?.length !== 0)
            //     )
            //         return
            // }
            materialServiceProcurementRequest
                .dtlListByEntity({ packageId: dtlId })
                .then(async res => {
                    // 整个清单的数据
                    if (this.tableData.length === 0) {
                        this.detailsData.forEach(() => {
                            this.tableData.push([])
                            this.cloneTableData.push([])
                        })
                    }
                    this.$set(this.tableData, dtlIndex, res)
                    this.cloneTableData[dtlIndex] = JSON.parse(JSON.stringify(res))
                    // await this.$emit('change', this.tempArr)
                    this.tableData[dtlIndex].forEach(item => {
                        item.changeType = 0
                    })
                    this.cloneTableData[dtlIndex].forEach(item => {
                        item.changeType = 0
                    })
                    // console.log('getdata this.cloneTableData', this.cloneTableData)
                    // 用于判断数据是否更新
                    // this.cloneTableData = JSON.parse(JSON.stringify(this.tableData))
                })
        },
        input (row) {
            // 综合单价（元） = 设备申报单价+运费申报单价
            row.unitPrice = isNaN(
                parseFloat((parseFloat(row.limitPrice) + parseFloat(row.freightPrice)).toFixed(2))
            )
                ? 0
                : parseFloat((parseFloat(row.limitPrice) + parseFloat(row.freightPrice)).toFixed(2))
            // 总金额（元）=数量*综合单价
            row.amount = isNaN(
                parseFloat((parseFloat(row.unitPrice) * parseFloat(row.num)).toFixed(2))
            )
                ? 0
                : parseFloat((parseFloat(row.unitPrice) * parseFloat(row.num)).toFixed(2))
        },
        // 如果数据修改了加上changeState1
        // 比较的是每一项
        ifEdit (tableData, cloneTableData) {
            let state = false
            if (tableData === undefined && cloneTableData === undefined) return
            // 判断每条数据
            tableData.forEach(item => {
                cloneTableData.forEach(item2 => {
                    // 判断数据是否修改
                    if (
                        item.recordId === item2.recordId &&
                        JSON.stringify(item) !== JSON.stringify(item2)
                    ) {
                        // 判断数量、运费单价、物资申报单价是否修改
                        if (item.num !== item2.num) {
                            item.isUpdateNumState = true
                        } else {
                            item.isUpdateNumState = false
                        }
                        if (item.limitPrice !== item2.limitPrice) {
                            item.isUpdateLimitPriceState = true
                        } else {
                            item.isUpdateLimitPriceState = false
                        }
                        if (item.freightPrice !== item2.freightPrice) {
                            item.isUpdateFreightPriceState = true
                        } else {
                            item.isUpdateFreightPriceState = false
                        }
                        state = true
                        item.changeType = 2
                    }
                })
            })
            // 边界情况：删除数据
            if (tableData.length !== cloneTableData.length) state = true
            // 边界情况：新增数据
            if (cloneTableData.length === 0) state = true
            // 边界情况：清单没数据没修改
            if (tableData.length === 0 && cloneTableData.length === 0) state = false
            return state
        },
        getNowDate () {
            // 个位数前补0
            const zeroFill = function (num) {
                if (parseInt(num) < 10) {
                    num = '0' + num
                }
                return num
            }
            let nowtime = new Date()
            nowtime =
                zeroFill(nowtime.getFullYear()) +
                '-' +
                zeroFill(nowtime.getMonth() + 1) +
                '-' +
                zeroFill(nowtime.getDate())
            return nowtime
        },
        // 清单验证
        tenderListRule () {
            if (this.tableData.length === 0) {
                this.ruleMessage = '请添加清单'
                this.$emit('onChangeTab', { name: 'tenderListCon' })
                return false
            }
            // 清单验证
            const ruleMessageArr = []
            if (this.tableData.length === 0) {
                return true
            }
            this.tableData.forEach((item, index) => {
                index += 1
                item.forEach((item2, index2) => {
                    index2 += 1
                    if (item2.num <= 0) {
                        ruleMessageArr.push(`包件${index}清单${index2}数量必须大于0`)
                    }
                    if (item2.limitPrice <= 0) {
                        ruleMessageArr.push(`包件${index}清单${index2}物资申报单价必须大于0`)
                    }
                    if (item2.freightPrice < 0) {
                        ruleMessageArr.push(`包件${index}清单${index2}运费申报单价必须大于等于0`)
                    }
                })
            })
            this.ruleMessage = ruleMessageArr.join(',')
            if (ruleMessageArr.length === 0) {
                return true
            } else {
                this.$emit('onChangeTab', { name: 'tenderList' })
                return false
            }
        },
        // 清单保存
        save () {
            // if (!this.tenderListRule()) return Promise.reject()
            new Promise(resolve => {
                let num = 0
                let length = this.detailsData.length
                this.detailsData.forEach(async (item, index) => {
                    // 当前清单对应的包件id
                    const dtlId = item.dtlId
                    const dtlIndex = this.detailsData.findIndex(item2 => dtlId === item2.dtlId)
                    // 是否修改数据
                    if (!this.ifEdit(this.tableData[index], this.cloneTableData[index])) {
                        length -= 1
                        return
                    }
                    const deleteTableData =
                        this.deleteTableData[index] === undefined ? [] : this.deleteTableData[index]
                    // console.log('deleteTableData', deleteTableData)
                    const tableData = [...this.tableData[index], ...deleteTableData]
                    // 更新清单
                    await materialServiceProcurementRequest.dtlSave(tableData)
                    await this.getData(dtlId, dtlIndex)
                    // 更新包件
                    // materialServiceProcurementRequest.packageCreate(this.detailsData)
                    num++
                    console.log('num', num)
                    console.log('length', length)
                    if (num === length) {
                        resolve()
                    }
                })
            }).then(() => {
                // 查询清单(不需要条件判断)
                // this.getData(0)
            })
            // if (!this.ifEdit(this.tableData)) return
            // // 加上删除数据
            // const tableData = [...this.tableData, ...this.deleteTableData]
            // materialServiceProcurementRequest.dtlSave(tableData)
            // 包件更新计划编号、招标最高限价
            // if (this.tableData.length !== 0) {
            //     // // 转成成后端需要的计划数据
            //     // const paln = JSON.stringify(
            //     //     Array.from(
            //     //         new Set(this.tableData.map(item => item.planDetails).filter(item => item))
            //     //     ).map(item => JSON.parse(item))
            //     // )
            //     // const priceLimit = this.tableData.reduce((prev, cur) => {
            //     //     return prev + cur.amount
            //     // }, 0)
            //     // 修改包件列表的计划编号（顺带一起保存了改变的价格数据）
            //     if (paln.length !== 0) {
            //         this.detailsData.forEach(item => {
            //             if (item.dtlId === this.dtlId) {
            //                 item.changeType = 2
            //                 item.planDetails = paln
            //                 // item.priceLimit = priceLimit
            //             }
            //         })
            //     }
            // } else {
            //     this.detailsData.forEach(item => {
            //         if (item.dtlId === this.dtlId) {
            //             item.changeType = 2
            //             item.planDetails = ''
            //             // item.priceLimit = 0
            //         }
            //     })
            // }
            // materialServiceProcurementRequest.packageCreate(this.detailsData)
            // console.log('palnArr', JSON.stringify(palnArr))
            // tableData.forEach((item)=>{})
        },
        getDetails () {
            this.detailsOfProposedArr = []
            if (this.detailsData.length !== 0) {
                this.detailsData.forEach((value, index) => {
                    if (value.dtlId !== '') {
                        this.detailsOfProposedArr.push({
                            label: value.name,
                            index
                        })
                    }
                })
            }
        },
        // 选择设备计划
        selectEquiPlan (PlanType2) {
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 获取已选择计划id
            const SelectedIDs =
                this.tableData[this.dtlIndex] !== undefined &&
                this.tableData[this.dtlIndex].map(item => item.materialId).filter(item => item)
                    .length !== 0
                    ? this.tableData[this.dtlIndex]
                        .map(item => item.materialId)
                        .filter(item => item)
                    : []
            if (PlanType2 === 1 || PlanType2 === 2) {
                // 设备大修计划、维保申请汇总
                selectDataClient({
                    SelectServiceToken: '/common/MaintenanceRepairSelect', // 客+户端对应方法名,
                    IsSingleMode: false, // 是否单选 true 单选 false 多选
                    SelectedIDs, // 已选中id
                    InitParamsStr: PlanType2 === 1 ? '2' : '1',
                    Title: PlanType2 === 1 ? '选择设备大修计划' : '选择维保申请汇总' // 标题
                }).then(val => {
                    // this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', '选择结果', function () {})
                    // 假数据
                    // let val = [
                    //     {
                    //         billNo: 'SRBCDXJH20220512001',
                    //         equipmentId: '1502126658530504706',
                    //         equipmentName: '设备A',
                    //         equipmentNo: 'SRBGLZ001',
                    //         id: '1526124049470255105',
                    //         isDetailed: true,
                    //         parentId: '1524560238133047297',
                    //         specificationModel: '',
                    //         unit: '',
                    //         billType: '大修计划'
                    //     }
                    // ]
                    // 过滤掉父级id
                    // val = val.filter(item => item.materialId)
                    // 过滤基础和计划相同规格的物资
                    val.forEach((item, index) => {
                        this.tableData[this.dtlIndex]?.forEach(item2 => {
                            const valStr =
                                item.materialClassName + item.materialName + item.spec + item.unit
                            const tableStr = item2.type + item2.name + item2.specs + item2.unit
                            // console.log('valStr', valStr)
                            // console.log('tableStr', tableStr)
                            if (valStr === tableStr) {
                                // console.log('index', index)
                                delete val[index]
                                // this.clientPop('err', '你已经选择了相同规格的物资')
                            }
                        })
                    })
                    val = val.filter(item => item !== null)
                    // 前端显示需要的数据格式
                    const arr = []
                    val.forEach((item, index) => {
                        arr.push({
                            amount: 0,
                            auditOpinion: '',
                            baseLibraryId: '',
                            billId: this.tenderId,
                            changeType: 1,
                            dataType: 1,
                            equipmentNumber: '',
                            equipmentStatus: 0,
                            freightPrice: 0,
                            isUpdateFreightPriceState: true,
                            isUpdateLimitPriceState: true,
                            isUpdateNumState: true,
                            limitPrice: 0,
                            maintenanceContent: '',
                            materialId: '',
                            materialNameId: '',
                            materialTypeId: '',
                            name: '',
                            num: 0,
                            packageId: this.dtlId,
                            planDetails: '',
                            recordId: '',
                            specs: '',
                            texture: '',
                            type: '',
                            unit: '',
                            unitPrice: 0
                        })
                        arr[index].equipmentNumber = item.equipmentNo
                        arr[index].name = item.equipmentName
                        arr[index].unit = item.unit
                        arr[index].specs = item.specificationModel
                        arr[index].materialNameId = item.equipmentId
                        // arr[index].materialTypeId = item.billType
                        arr[index].planDetails = JSON.stringify({
                            billid: item.billId,
                            billNo: item.billNo,
                            type: PlanType2
                        })
                    })
                    // val.forEach((item, index) => {})
                    // console.log(' this.tableData', this.tableData, this.tableData[this.dtlIndex])
                    console.log('arr', arr)
                    this.tableData[this.dtlIndex].push(...arr)
                    console.log('request', this.tableData, this.dtlIndex)
                })
            } else {
                // 设备台账
                selectDataClient({
                    SelectServiceToken: '/facilityaccount/account/all/equipment', // 客+户端对应方法名,
                    IsSingleMode: false, // 是否单选 true 单选 false 多选
                    SelectedIDs, // 已选中id
                    InitParamsStr: JSON.stringify({
                        orgId: '',
                        states: []
                    }),
                    Title: '选择设备台账' // 标题
                }).then(val => {
                    // this.setSelectedInfo(val)
                    // openAppClient('/showSelectedData', '选择结果', function () {})
                    // 假数据
                    // let val = [
                    //     {
                    //         accountId: '1514149003587678210',
                    //         accountStatus: null,
                    //         categoryId: '',
                    //         categoryName: '',
                    //         equipmentCondition: 0,
                    //         equipmentId: '',
                    //         equipmentName: '设备122',
                    //         equipmentNo: '51613121213224',
                    //         equipmentState: null,
                    //         oneLevelCategoryId: null,
                    //         oneLevelCategoryName: null,
                    //         orgId: '1439990097591140354',
                    //         orgName: '四川公路桥梁建设集团有限公司',
                    //         originalNo: 'SRBGSBDD20220413003',
                    //         specificationModel: '',
                    //         receiveId: '1514149031022620673',
                    //         nature: '1',
                    //         unit: '天'
                    //     }
                    // ]
                    // 过滤掉父级id
                    // val = val.filter(item => item.materialId)
                    // 过滤基础和计划相同规格的物资
                    val.forEach((item, index) => {
                        this.tableData[this.dtlIndex]?.forEach(item2 => {
                            const valStr =
                                item.materialClassName + item.materialName + item.spec + item.unit
                            const tableStr = item2.type + item2.name + item2.specs + item2.unit
                            // console.log('valStr', valStr)
                            // console.log('tableStr', tableStr)
                            if (valStr === tableStr) {
                                // console.log('index', index)
                                delete val[index]
                                // this.clientPop('err', '你已经选择了相同规格的物资')
                            }
                        })
                    })
                    val = val.filter(item => item !== null)
                    // 前端显示需要的数据格式
                    const arr = []
                    val.forEach((item, index) => {
                        arr.push({
                            amount: 0,
                            auditOpinion: '',
                            baseLibraryId: '',
                            billId: this.tenderId,
                            changeType: 1,
                            dataType: 2,
                            equipmentNumber: '',
                            equipmentStatus: 0,
                            freightPrice: 0,
                            isUpdateFreightPriceState: true,
                            isUpdateLimitPriceState: true,
                            isUpdateNumState: true,
                            limitPrice: 0,
                            maintenanceContent: '',
                            materialId: '',
                            materialNameId: '',
                            materialTypeId: '',
                            name: '',
                            num: 0,
                            packageId: this.dtlId,
                            planDetails: '',
                            recordId: '',
                            specs: '',
                            texture: '',
                            type: '',
                            unit: '',
                            unitPrice: 0
                        })
                        arr[index].equipmentNumber = item.equipmentNo
                        arr[index].name = item.equipmentName
                        arr[index].unit = item.unit
                        arr[index].specs = item.specificationModel
                        arr[index].materialNameId = item.equipmentId
                        arr[index].materialTypeId = item.categoryId
                        arr[index].planDetails = JSON.stringify({
                            billid: item.billId,
                            billNo: item.billNo,
                            type: PlanType2
                        })
                    })
                    // val.forEach((item, index) => {})
                    // console.log(' this.tableData', this.tableData, this.tableData[this.dtlIndex])
                    this.tableData[this.dtlIndex].push(...arr)
                    // console.log('request', this.tableData, this.dtlIndex)
                })
            }
        },
        // 选择物资基础库
        selectBaseLibrary () {
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 获取已选择基础id
            const SelectedIDs =
                this.tableData[this.dtlIndex].map(item => item.baseLibraryId).filter(item => item)
                    .length !== 0
                    ? this.tableData[this.dtlIndex]
                        .map(item => item.baseLibraryId)
                        .filter(item => item)
                    : []
            SelectedIDs
            // console.log('SelectedIDs', SelectedIDs)
            selectDataClient({
                SelectServiceToken: '/material/categoryLibrary/queryListByParentClassId2', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs, // 已选中id
                Title: '选择物资基础库' // 标题
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                // 假数据
                // let val = [
                //     {
                //         billId: '1492034624291868674',
                //         classIdPath: '1492338036615155713/1492338402287161345/1492339386505760770',
                //         className: '一级钢材',
                //         classNamePath: '主要材料/建筑钢材/一级钢材',
                //         materialName: '钢材0004',
                //         spec: '规格4',
                //         unit: 'T'
                //     },
                //     {
                //         billId: '1492034594352926722',
                //         classIdPath: '1492338036615155713/1492338402287161345/1492339386505760770',
                //         className: '一级钢材',
                //         classNamePath: '主要材料/建筑钢材/一级钢材',
                //         materialName: '钢材0003',
                //         spec: '规格3',
                //         unit: 'T'
                //     }
                // ]
                // 过滤基础和计划相同规格的物资
                val.forEach((item, index) => {
                    this.tableData[this.dtlIndex].forEach(item2 => {
                        const valStr =
                            item.classNamePath + item.materialName + item.spec + item.unit
                        const tableStr = item2.type + item2.name + item2.specs + item2.unit
                        if (valStr === tableStr) {
                            // console.log('index', index)
                            delete val[index]
                            // this.clientPop('err', '你已经选择了相同规格的物资')
                        }
                    })
                })
                val = val.filter(item => item !== null)
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                const arr = []
                val.forEach((item, index) => {
                    arr.push({
                        amount: 0,
                        auditOpinion: '',
                        baseLibraryId: '',
                        billId: this.tenderId,
                        changeType: 1,
                        dataType: 2,
                        equipmentNumber: '',
                        equipmentStatus: 0,
                        freightPrice: 0,
                        isUpdateFreightPriceState: true,
                        isUpdateLimitPriceState: true,
                        isUpdateNumState: true,
                        limitPrice: 0,
                        maintenanceContent: '',
                        materialId: '',
                        materialNameId: '',
                        materialTypeId: '',
                        name: '',
                        num: 0,
                        packageId: this.dtlId,
                        planDetails: '',
                        recordId: '',
                        specs: '',
                        texture: '',
                        type: '',
                        unit: '',
                        unitPrice: 0
                    })
                    arr[index].name = item.materialName
                    arr[index].specs = item.spec
                    arr[index].unit = item.unit
                    arr[index].type = item.classNamePath
                    arr[index].baseLibraryId = item.billId
                    arr[index].materialNameId = item.billId
                    arr[index].materialTypeId = item.classIdPath
                })
                // console.log('this.dtlIndex', this.dtlIndex)
                this.tableData[this.dtlIndex].push(...arr)
                console.log('this.tableData', this.tableData)
                // this.setSelectedInfo(this.tableData)
                // openAppClient('/showSelectedData', '选择结果', function () {})
            })
        },
        // 选择设备基础库
        selectEquiBaseLibrary () {
            if (this.dtlId === '') {
                this.clientPop('err', '请先添加包件')
                return
            }
            // 获取已选择基础id
            const SelectedIDs =
                this.tableData[this.dtlIndex].map(item => item.baseLibraryId).filter(item => item)
                    .length !== 0
                    ? this.tableData[this.dtlIndex]
                        .map(item => item.baseLibraryId)
                        .filter(item => item)
                    : []
            const InitParamsStr = {
                categoryId: '00000',
                isUpdate: false,
                keyword: ''
            }
            // console.log('SelectedIDs', SelectedIDs)
            selectDataClient({
                SelectServiceToken: '/facilitybase/equipment/getEquipmentCategoryAll', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs, // 已选中id
                InitParamsStr: JSON.stringify(InitParamsStr),
                Title: '选择设备基础库' // 标题
            }).then(val => {
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                // 假数据
                // let val = [
                //     {
                //         categoryId: 'a94514983e61-87e2-2748-6bb8-c5662738',
                //         categoryName: '装载机',
                //         equipmentId: '1555094214517911553',
                //         equipmentName: '111222',
                //         founderId: '',
                //         founderName: '',
                //         gmtCreate: '2022-08-04 00:00:00',
                //         gmtModified: null,
                //         guidanceBuyPrice: 0,
                //         guidanceLeasePrice: 0,
                //         innerAllocationPrice: 0,
                //         isUsed: '',
                //         marketBuyPrice: 0,
                //         marketLeasePrice: 0,
                //         modifier: '',
                //         modifierId: '',
                //         oneLevelCategoryId: 'a945146e50c5-aaf1-5042-8ec9-203b2714',
                //         oneLevelCategoryName: '土方及压实设备',
                //         recorder: 'PCWP测试',
                //         recorderId: '',
                //         remarks: '1111',
                //         specificationModel: '',
                //         state: 1,
                //         unit: '台',
                //         workId: ''
                //     },
                //     {
                //         categoryId: 'a9451492afa5-8f7d-3a4c-d06b-3b905be2',
                //         categoryName: '推土机',
                //         equipmentId: 'ae7e18eb35d5-b6ed-ce46-5c24-9ab858ad',
                //         equipmentName: '1',
                //         founderId: 'abb5184d43ca-960c-b640-c36c-454a10f4',
                //         founderName: 'PCWP测试',
                //         gmtCreate: '2022-04-21 00:00:00',
                //         gmtModified: '2022-04-21 00:00:00',
                //         guidanceBuyPrice: 0,
                //         guidanceLeasePrice: 0,
                //         innerAllocationPrice: 0,
                //         isUsed: '0',
                //         marketBuyPrice: 0,
                //         marketLeasePrice: 0,
                //         modifier: 'PCWP测试',
                //         modifierId: 'abb5184d43ca-960c-b640-c36c-454a10f4',
                //         oneLevelCategoryId: 'a945146e50c5-aaf1-5042-8ec9-203b2714',
                //         oneLevelCategoryName: '土方及压实设备',
                //         recorder: 'PCWP测试',
                //         recorderId: 'abb5184d43ca-960c-b640-c36c-454a10f4',
                //         remarks: null,
                //         specificationModel: null,
                //         state: 1,
                //         unit: 'kg',
                //         workId: null
                //     }
                // ]
                // 过滤基础和计划相同规格的物资
                val.forEach((item, index) => {
                    this.tableData[this.dtlIndex].forEach(item2 => {
                        const valStr =
                            item.classNamePath + item.materialName + item.spec + item.unit
                        const tableStr = item2.type + item2.name + item2.specs + item2.unit
                        if (valStr === tableStr) {
                            // console.log('index', index)
                            delete val[index]
                            // this.clientPop('err', '你已经选择了相同规格的物资')
                        }
                    })
                })
                val = val.filter(item => item !== null)
                // this.setSelectedInfo(val)
                // openAppClient('/showSelectedData', '选择结果', function () {})
                const arr = []
                val.forEach((item, index) => {
                    arr.push({
                        amount: 0,
                        auditOpinion: '',
                        baseLibraryId: '',
                        billId: this.tenderId,
                        changeType: 1,
                        dataType: 2,
                        equipmentNumber: '',
                        equipmentStatus: 0,
                        freightPrice: 0,
                        isUpdateFreightPriceState: true,
                        isUpdateLimitPriceState: true,
                        isUpdateNumState: true,
                        limitPrice: 0,
                        maintenanceContent: '',
                        materialId: '',
                        materialNameId: '',
                        materialTypeId: '',
                        name: '',
                        num: 0,
                        packageId: this.dtlId,
                        planDetails: '',
                        recordId: '',
                        specs: '',
                        texture: '',
                        type: '',
                        unit: '',
                        unitPrice: 0
                    })
                    arr[index].name = item.equipmentName
                    arr[index].specs = item.specificationModel
                    arr[index].unit = item.unit
                    // arr[index].type = item.classNamePath
                    // arr[index].baseLibraryId = item.billId
                    arr[index].materialNameId = item.equipmentId
                    arr[index].materialTypeId = item.categoryId
                    // texture
                })
                // console.log('this.dtlIndex', this.dtlIndex)
                this.tableData[this.dtlIndex].push(...arr)
                console.log('this.tableData', this.tableData)
                // this.setSelectedInfo(this.tableData)
                // openAppClient('/showSelectedData', '选择结果', function () {})
            })
        },
        handleNodeClick (dtlId) {
            const item = this.detailsData.find(item2 => item2.dtlId === dtlId)
            this.selectDetailState = true
            // 获取清单数据
            this.dtlId = item.dtlId
            // console.log('data', data)
            // console.log('node', node)
            // console.log('el', el)
        },
        // async findByApplyId () {
        //     let data = []
        //     let leftTree = []
        //     if (this.detailsOfProposed.length !== 0) {
        //         data = this.detailsOfProposed
        //     } else {
        //         await applyRequest.bidPackageListByBillId(this.tenderId).then(res => {
        //             data = res
        //             // this.detailsOfProposedArr = res
        //             // this.tableData.forEach(value => {
        //             //     // table显示需要的字段
        //             //     value.subcontractorName =
        //             //         (value.subcontractor[0] && value.subcontractor[0].subcontractorId) || ''
        //             // })
        //             // this.pagination.total = res.totalCount || res.length
        //         })
        //     }
        //     data.forEach(value => {
        //         leftTree.push({ label: value.name })
        //     })
        //     this.detailsOfProposedArr = leftTree
        // },
        openNewPage (name) {
            this.$notify.closeAll()
            if (name === 'tenderList') {
                const params = JSON.stringify({
                    // 正式环境应该不用转换
                    title: '选择清单',
                    url: '',
                    method: 'get',
                    params: { tenderId: this.tenderId }, // 基础id获取包件
                    tableColumnAttr: this.orgSelectTableColumnAttr,
                    tableColumnWidth: this.selectTableColumnWidth,
                    ifPagination: 0
                })
                this.$notify({
                    title: '选择清单',
                    dangerouslyUseHTMLString: true,
                    message: `正式环境：客户端打开新页面<br>
                测试环境：手动打开新页面<br>
                <textarea cols="35" rows="10">http://localhost:8080/selectData?params=${params}</textarea>
                <br><br>
                回调参数：<br>
                <textarea cols="35" rows="3" id="callBackData"></textarea><br>
                <button id="getPopData">执行回调方法</button>
                `,
                    duration: 0
                })
                document.querySelector('#getPopData').addEventListener('click', this.orgGetPopData)
            }
        }
    }
}
</script>
<style lang="scss" scoped>
.ruleMessage {
    margin-bottom: 20px;
    color: red;
}
</style>
